﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PtlSave.Util
{
    /*
     * 获取（key）始终是唯一的时间戳
     * 精度：毫秒
     */
    public class HiResDateTime
    {
        //keys
        private static Dictionary<string, object> _timeLocks = new Dictionary<string, object>() { { "dft", new object() } };
        // records the 64-bit tick value of the last time
        private static Dictionary<string, long> _lastTime = new Dictionary<string, long>() { { "dft", 0 } };

        /*
         * key:唯一键值
         * format:yyyy-MM-dd HH:mm:ss.fff
         * 精度：毫秒 匹配涛思数据库时间戳最小精度
         */
        public static string GetCurrentTime(string key = "dft")
        {
            if (!_timeLocks.ContainsKey(key))
            {
                _timeLocks.Add(key, new object());
                _lastTime.Add(key, 0);
            }
            lock (_timeLocks[key])
            { // prevent concurrent access to ensure uniqueness
                DateTime dt = DateTime.Now;
                //Ticks除以10000为毫秒
                //毫秒除以1000为秒
                if ((long)(dt.Ticks / 10000) <= (long)(_lastTime[key]/1000))
                {
                    //增加1毫秒
                    dt = new DateTime(_lastTime[key] + 10000);
                }
                _lastTime[key] = dt.Ticks;
                return string.Format("{0:yyyy-MM-dd HH:mm:ss.fff}", dt);
            }
        }
    }
}
